//
//  LLAlertView.m
//  textAlertView
//
//  Created by lv xingtao on 12-10-13.
//  Copyright (c) 2012年 lv xingtao. All rights reserved.
//
#import "LLSmallUtil.h"
#import "MBProgressHUD.h"
#import "LLAlertView.h"


@implementation LLAlertView


- (id)initWithTitle:(NSString *)title 
            message:(NSString *)message 
           delegate:(id)delegate 
  cancelButtonTitle:(NSString *)cancelButtonTitle 
   otherButtonTitle:(NSString *)otherButtonTitle
{
    self = [super initWithFrame:CGRectMake(0, 0, 320, 568)];
    if (self != nil)
    {
        self.delegate = delegate;
        
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        
        UIView *backBgView = [[UIView alloc] initWithFrame:CGRectMake(43, 135, 235, 128)];
        backBgView.backgroundColor = [UIColor whiteColor];
        [self addSubview:backBgView];
        backBgView.layer.cornerRadius = 5;
        backBgView.clipsToBounds = YES;
        //        backBgView.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.3].CGColor;
        //        backBgView.layer.borderWidth = 0.6f;
        
        UIView *titleBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backBgView.width, 28)];
        titleBg.backgroundColor = [UIColor whiteColor];
        [backBgView addSubview:titleBg];
        
        UILabel *titleLabel = [self createLabelwithTitle:title withFont:16];
        titleLabel.size = titleBg.size;
        [backBgView addSubview:titleLabel];
        
        //        UIView *backLineView = [[[UIView alloc] initWithFrame:CGRectMake(0, titleLabel.bottom + 10, 280, 1)] autorelease];
        //        backLineView.backgroundColor = [UIColor blackColor];
        //        [backBgView addSubview:backLineView];
        
        UILabel *msgLabel = [self createLabelwithTitle:message withFont:14];
        msgLabel.text = message;
        msgLabel.origin = CGPointMake(15, 36);
        msgLabel.contentMode = UIViewContentModeTop;
        msgLabel.width = backBgView.width - 15 * 2;
        msgLabel.numberOfLines = 5;
        msgLabel.textAlignment = NSTextAlignmentCenter;
        //msgLabel.textColor = [LLStyle textColor];
        //[msgLabel sizeToFit];
        [backBgView addSubview:msgLabel];
        
        UIButton *cancelBtn = nil;
        if (cancelButtonTitle != nil)
        {
            cancelBtn = [self createCancelBtn];
            if (otherButtonTitle == nil) {
                
                //cancelBtn = [self createConfirmBtn];
            }
            
            [cancelBtn setTitle:cancelButtonTitle forState:UIControlStateNormal];
            [backBgView addSubview:cancelBtn];
            cancelBtn.tag = 100;
        }
        
        UIButton *otherBtn = nil;
        if (otherButtonTitle != nil)
        {
            otherBtn = [self createConfirmBtn];
            [otherBtn setTitle:otherButtonTitle forState:UIControlStateNormal];
            [backBgView addSubview:otherBtn];
            otherBtn.tag = 101;
        }
        
        if (otherBtn && cancelBtn) 
        {
            // 一行两个
            otherBtn.left = 8;
            cancelBtn.right = backBgView.width - 8;
        }
        else
        {
            
            [backBgView adjustViewLineCenter:otherBtn];
            [backBgView adjustViewLineCenter:cancelBtn];
        }
    }
    return self;
}

- (UILabel*)createLabelwithTitle:(NSString*)title
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 270, 40)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    label.textColor = [UIColor blackColor];
    label.text = title;
    label.textAlignment = NSTextAlignmentCenter;
    
    return label;
}

- (UILabel*)createLabelwithTitle:(NSString*)title withFont:(int)fontSize
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 270, 40)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:fontSize];
    label.textColor = [UIColor whiteColor];
    label.text = title;
    label.textAlignment = NSTextAlignmentCenter;
    
    return label;
}

- (UIButton*)createCancelBtn
{
    UIButton *button = [[UIButton alloc] init];
    button.frame = CGRectMake(110, 90, 105, 28);
    [button addTarget:self action:@selector(hideWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (UIButton*)createConfirmBtn
{
    UIButton *button = [[UIButton alloc] init];;
    button.frame = CGRectMake(110, 90, 105, 28);
    [button addTarget:self action:@selector(hideWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (void)show
{
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
    
    //[LLErrorAlertTipView showTitle:@"测试123412341234" onView:self withLinkView:[self viewWithTag:100]];
}

- (void)hideWithBtn:(UIButton*)btn
{
    [self.delegate alertView:(id)self didDismissWithButtonIndex:btn.tag-100];
    
    [self removeFromSuperview];
}
@end

@implementation LLToastView
{
    UILabel *titleLabel;
    UIView *backBgView;
}
- (id)initWithTipTitle:(NSString *)tipTitle
           contentView:(UIView *)contentView
              delegate:(id)delegate
     cancelButtonTitle:(NSString *)cancelButtonTitle
      otherButtonTitle:(NSString *)otherButtonTitle
{
    
    self = [super initWithFrame:CGRectMake(0, 0, 320, 568)];
    if (self != nil)
    {
        self.delegate = delegate;
        
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        //contentView.size.height   87 ？ 162
        
        UIFont *tipFont = [UIFont systemFontOfSize:12];
        UIColor *tipColor = [UIColor colorWithHTMLStr:@"666666"];
        
        backBgView = [[UIView alloc] initWithFrame:CGRectMake(16, 135, 288, 43 + 43 + contentView.size.height)];
        backBgView.backgroundColor = [UIColor whiteColor];
        [self addSubview:backBgView];
        backBgView.clipsToBounds = YES;
        
        UIView *titleBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backBgView.width, 28)];
        titleBg.backgroundColor = [UIColor whiteColor];
        [backBgView addSubview:titleBg];
        
        titleLabel = [self createLabelwithTitle:tipTitle withFont:15];
        titleLabel.top = (43 - titleLabel.height)/2;
        titleLabel.left = (288 - titleLabel.width)/2;
        titleLabel.font = tipFont;
        titleLabel.textColor = tipColor;
        [backBgView addSubview:titleLabel];
        
        UIView *lineTitle = [self createLine:YES];
        lineTitle.top = 43;
        [backBgView addSubview:lineTitle];
        
        UIView *contentDetailView = contentView;
        contentView.top = 43;
        [backBgView addSubview:contentDetailView];
        
        UIView *bottomLine = [self createLine:YES];
        bottomLine.top = 42 + contentView.size.height;
        [backBgView addSubview:bottomLine];
        
        UIButton *cancelBtn = nil;
        if (cancelButtonTitle != nil)
        {
            UIFont *cancelFont = [UIFont systemFontOfSize:12];
            UIColor *cancelColor = [UIColor colorWithHTMLStr:@"666666"];
            
            cancelBtn = [self createCancelBtn];
            if (otherButtonTitle == nil) {
                
                //cancelBtn = [self createConfirmBtn];
            }
            cancelBtn.top = 43 + contentView.size.height;
            
            [cancelBtn setTitle:cancelButtonTitle forState:UIControlStateNormal];
            [cancelBtn setTitleColor:cancelColor forState:UIControlStateNormal];
            cancelBtn.titleLabel.font = cancelFont;
            [backBgView addSubview:cancelBtn];
            cancelBtn.tag = 100;
        }
        
        _otherBtn = nil;
        if (otherButtonTitle != nil)
        {
            UIFont *otherButtonFont = [UIFont systemFontOfSize:12];
            UIColor *otherButtonColor = [UIColor colorWithHTMLStr:@"000000"];
            
            _otherBtn = [self createConfirmBtn];
            _otherBtn.top = 43 + contentView.size.height;
            [_otherBtn setTitle:otherButtonTitle forState:UIControlStateNormal];
            [_otherBtn setTitleColor:otherButtonColor forState:UIControlStateNormal];
            _otherBtn.titleLabel.font = otherButtonFont;
            [backBgView addSubview:_otherBtn];
            _otherBtn.tag = 101;
        }
        
        UIView *verticalLine = [self createLine:NO];
        verticalLine.top = 43 + contentView.size.height;
        verticalLine.left = 144;
        [backBgView addSubview:verticalLine];
        
        if (_otherBtn && cancelBtn)
        {
            // 一行两个
            cancelBtn.left = 0;
            _otherBtn.left = 144;
        }
        else if(otherButtonTitle != nil)
        {
            [verticalLine removeFromSuperview];
            _otherBtn.left = 0;
            _otherBtn.width = 288;
        }
        else
        {
            [verticalLine removeFromSuperview];
            cancelBtn.width = 288;
        }
        
        
    }
    return self;
}

- (UIView *)createLine:(BOOL)isLongLine
{
    UIView *line = [[UIView alloc] init];
    if (isLongLine)
    {
        line.frame = CGRectMake(0, 0, 288, 0.6);
    }
    else
    {
        line.frame = CGRectMake(0, 0, 0.6, 43);
    }
    line.backgroundColor = [UIColor colorWithWhite:199/255.0 alpha:0.8];
    return line;
}

- (UILabel*)createLabelwithTitle:(NSString*)title withFont:(int)fontSize
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 288, 43)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:fontSize];
    label.textColor = [UIColor blackColor];
    label.text = title;
    label.textAlignment = NSTextAlignmentCenter;
    [label sizeToFit];
    
    return label;
}


- (UIButton*)createCancelBtn
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor colorWithR:239 G:241 B:243 A:1];
    button.frame = CGRectMake(0, 0, 144, 43);
    [button addTarget:self action:@selector(hideWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (UIButton*)createConfirmBtn
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor colorWithR:239 G:241 B:243 A:1];
    button.frame = CGRectMake(144, 0, 144, 43);
    [button addTarget:self action:@selector(hideWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}


- (void)show
{
    if (_needLogo) {
        UIImage *logoImage = [UIImage sdkBundleImageNamed:@"logo2"];
        UIImageView *logoView = [[UIImageView alloc] initWithImage:logoImage];
        logoView.frame = CGRectMake(0, (43 - logoImage.size.height)/2, logoImage.size.width, logoImage.size.height);
        logoView.left = (320 - (logoView.width + titleLabel.width))/2 - 10;
        titleLabel.left = logoView.right + 5;
        [backBgView addSubview:logoView];
    }
    
    if (_moreLogo)
    {
        UIImage *moreLogoImage = [UIImage sdkBundleImageNamed:@"wenhao"];
        UIButton *moreLogoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moreLogoButton setBackgroundImage:moreLogoImage];
        moreLogoButton.frame = CGRectMake(288 - 8 - moreLogoImage.size.width , (43 - moreLogoImage.size.height)/2, moreLogoImage.size.width, moreLogoImage.size.height);
        [backBgView addSubview:moreLogoButton];
    }
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
}

- (void)hideWithBtn:(UIButton*)btn
{
    [self.delegate alertView:(id)self didDismissWithButtonIndex:btn.tag-100];
    
    [self removeFromSuperview];
}

- (void)setNeedLogo:(BOOL)needLogo
{
    _needLogo = needLogo;
}

- (void)setMoreLogo:(BOOL)moreLogo
{
    _moreLogo = moreLogo;
//    if (_needLogo || _moreLogo) {
//        [self setNeedsDisplay];
//    }
}

@end


@implementation LLErrorAlertTipView

- (void)dealloc
{
    self.arrowView = nil;
    self.contentView = nil;
}

- (id)initTitle:(NSString*)title
{
    self = [super init];
    if (self != nil) {
        
        
        int fontSize = 14;
        
        CGSize fitSize = [title sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}];
        self.frame = CGRectMake(0, 0, fitSize.width + 20, fitSize.height + 10);
        
        //self.layer
        
        UIView *backBgView = [[UIView alloc] initWithFrame:CGRectMake(-10, 6, fitSize.width + 20, fitSize.height + 6)];
        backBgView.backgroundColor = [UIColor colorWithR:255 G:60 B:0 A:1];
        [self addSubview:backBgView];
        backBgView.layer.cornerRadius = backBgView.height/2;
        self.contentView = backBgView;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 3, fitSize.width, fitSize.height)];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:fontSize];
        label.textColor = [UIColor whiteColor];
        label.text = title;
        [self.contentView addSubview:label];
        
        self.arrowView = [UIImageView imageViewWithName:@"js3.png"];
        [self addSubview:self.arrowView];
        self.arrowView.left = -5;
        
    }
    return self;
}

- (void)adjustFrameToLinkView:(UIView*)linkView
{
    CGPoint arrowPoint = [linkView convertPoint:linkView.center toView:[UIApplication sharedApplication].keyWindow];
    
    self.arrowView.left = arrowPoint.x - self.arrowView.width/2;
    
    if (arrowPoint.x < 200) {
        //self.contentLabel.left = 
    }
    
}

+ (LLErrorAlertTipView*)showTitle:(NSString*)title onView:(UIView*)containView withLinkView:(UIView*)linkView
{
    LLErrorAlertTipView *errorTipView = [[LLErrorAlertTipView alloc] initTitle:title];
    
    CGPoint linkCenterBottomPoint = CGPointMake(linkView.width / 2, linkView.height);
    CGPoint originPoint = [linkView convertPoint:linkCenterBottomPoint toView:containView];
    
    errorTipView.origin = originPoint;
    
    [containView addSubview:errorTipView];
    
    CGPoint arrowPoint = [linkView convertPoint:linkView.center toView:[UIApplication sharedApplication].keyWindow];
    
    if (arrowPoint.x > 200) {
        errorTipView.contentView.left -= (errorTipView.contentView.width - 30);
    }
    
    return errorTipView;
}

@end

static DismissBlock _dismissBlock;
static CancelBlock _cancelBlock;

@implementation LLAlertService

+ (void)alertWithTip:(NSString *)tipString
{
    // 防止多次调用
    UIView *presentView = [[[UIApplication sharedApplication] delegate] window];
    
    LLMBProgressHUD *hud = [[LLMBProgressHUD alloc] initWithView:presentView];
    hud.offsetY = - 50;
    hud.minShowTime = 1.5;
    [hud setLabelText:tipString];
    hud.customView = [[UIView alloc] init];
    hud.mode = LLMBProgressHUDModeCustomView;
    [presentView addSubview:hud];
    [hud show:YES];
    [hud hide:YES];
    hud.removeFromSuperViewOnHide = YES;
}

+ (void)alertWithTip:(NSString*)tipString completeBlock:(void (^)())block
{
    UIView *presentView = [[[UIApplication sharedApplication] delegate] window];
    
    LLMBProgressHUD *hud = [[LLMBProgressHUD alloc] initWithView:presentView];
    hud.offsetY = - 50;
    hud.minShowTime = 1.5;
    [hud setLabelText:tipString];
    hud.customView = [[UIView alloc] init];
    hud.mode = LLMBProgressHUDModeCustomView;
    [presentView addSubview:hud];
    [hud show:YES];
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:1.5];
    
    [hud showAnimated:YES whileExecutingBlock:^{
        sleep(1.5);
    } completionBlock:block];
    
}

+ (UIView*)waitingWithTip:(NSString*)tipString
{
    UIView *presentView = [[[UIApplication sharedApplication] delegate] window];
    
    LLMBProgressHUD *hud = [[LLMBProgressHUD alloc] initWithView:presentView];
    hud.offsetY = - 50;
    //hud.minShowTime = 1;
    [hud setLabelText:tipString];
    [presentView addSubview:hud];
    [hud show:YES];
    //[hud hide:YES];
    hud.removeFromSuperViewOnHide = YES;
    
    return hud;
}

+ (void)hideWaitingView:(UIView*)waitingView
{
    if ([waitingView isKindOfClass:[LLMBProgressHUD class]])
    {
        [(LLMBProgressHUD*)waitingView hide:YES];
    }
    else
    {
        [waitingView removeFromSuperview];
    }
}

+ (void)alertWithTip:(NSString*)tipMsg withTitle:(NSString*)title
{
    LLAlertView *alert = [[LLAlertView alloc] initWithTitle:title
                                                    message:tipMsg 
                                                   delegate:nil 
                                          cancelButtonTitle:@"确认" 
                                           otherButtonTitle:nil];
    [alert show];
}

+ (void)sysAlertWithTip:(NSString*)tipMsg withTitle:(NSString*)title
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:tipMsg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil, nil];
    [alert show];
}

+ (void) showAlertViewWithTitle:(NSString*) title                    
                        message:(NSString*) message 
              cancelButtonTitle:(NSString*) cancelButtonTitle
              otherButtonTitles:(NSArray*) otherButtons
                      onDismiss:(DismissBlock) dismissed                   
                       onCancel:(CancelBlock) cancelled {
    
    _cancelBlock  = [cancelled copy];
    
    _dismissBlock  = [dismissed copy];
    
    NSString *otherTitle = nil;
    if (otherButtons.count > 0) {
        otherTitle = [otherButtons objectAtIndex:0];
    }
    
//    LLAlertView *alert = [[LLAlertView alloc] initWithTitle:title
//                                                    message:message
//                                                   delegate:[self self]
//                                          cancelButtonTitle:cancelButtonTitle
//                                           otherButtonTitle:otherTitle];
    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:title
                                                   message:message
                                                  delegate:self
                                         cancelButtonTitle:cancelButtonTitle
                                         otherButtonTitles:otherTitle,nil];
    
    
    //    for(NSString *buttonTitle in otherButtons)
    //    {
    //        [alert addButtonWithTitle:buttonTitle];
    //    }
    
    //  [alert setDimsBackground:NO];
    [alert show];
    //return [alert autorelease];
}

+ (void)alertView:(UIAlertView*) alertView didDismissWithButtonIndex:(NSInteger) buttonIndex {
    
	if(buttonIndex == 0)//[alertView cancelButtonIndex])
	{
		_cancelBlock();
	}
    else
    {
        _dismissBlock(buttonIndex - 1); // cancel button is button 0
    }  
}

@end

@implementation LLNetAlert

- (id)init
{
    self = [super init];
    if (self) {
        [self listenNetAlert];
    }
    return self;
}

- (void)dealloc
{
    [self unListenNetAlert];
}

- (void)listenNetAlert
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(showWait:)
                                                 name:kNetWaitingNotify
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(hideWait)
                                                 name:kNetWaitingDoneNotify
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(showErrorAlert:)
                                                 name:kNetErrorAlertNothify
                                               object:nil];
    
}

- (void)unListenNetAlert
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)showWait:(NSNotification*)notify
{
    if (waitingView == nil)
    {
        waitingView = [LLAlertService waitingWithTip:notify.userInfo[@"msg"]];
    }
    waitingCount++;
}

- (void)hideWait
{
    waitingCount--;
    if (waitingCount <= 0)
    {
        [LLAlertService hideWaitingView:waitingView];
        waitingView = nil;
        waitingCount = 0;
    }
}

- (void)showErrorAlert:(NSNotification*)notify
{
    [LLAlertService alertWithTip:notify.userInfo[@"msg"]];
}

@end